package com.grom.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.dispacher.config.GlobalConfig;
import com.dispacher.context.ContextHolder;
import com.grom.po.BrandVisitHistory;
import com.grom.po.ContactInfo;
import com.grom.po.Customer;
import com.grom.service.BrandHistoryService;
import com.grom.service.ContactInfoService;
import com.grom.service.CustomerService;
import com.grom.util.Constants;
import com.grom.util.IDCreator;
import com.grom.util.JsonUtil;
import com.grom.util.SecurityUtil;
import com.holder.log.ConsoleLog;

public class CustomerAction {
	int pageSize = Integer.valueOf(GlobalConfig
			.getProperty(Constants.KEY_PAGE_SIZE));

	public void gotoList() {
		List<Customer> allCustomer = CustomerService.instance.getAllCustomer();
		allCustomer = getUserBindCustomer(allCustomer);
		ContextHolder.setRequestAttribute("allCustomer", allCustomer);
		ContextHolder.forward("/WEB-INF/jsp/customer/update.jsp");
	}

	public void gotoQuery() {
		List<Customer> allCustomer = CustomerService.instance.getAllCustomer();
		ContextHolder.setRequestAttribute("allCustomer", allCustomer);
		for (Customer cus : allCustomer) {
			ConsoleLog.debug(JsonUtil.parseToJson(cus));
		}
		ContextHolder.forward("/WEB-INF/jsp/customer/query.jsp");
	}

	public void doSave() {
		Customer customer = (Customer) ContextHolder
				.initFromTheRequest(Customer.class);
		String historyInfos = ContextHolder.findInstance().getRequest().getParameter("historyInfo");
		List<BrandVisitHistory> historyList = parseToHistorys(historyInfos);
		String contacts = ContextHolder.findInstance().getRequest()
				.getParameter("contactInfo");
		List<ContactInfo> conList = parseToContactInfo(contacts);
		ConsoleLog.debug(" | CustomerAction | doSaveForSearch | contacts | "
				+ contacts);
		if (customer.getID() == null || customer.getID().trim().equals("")) {
			CustomerService.instance.add(customer, conList,historyList);
		} else {
			CustomerService.instance.update(customer, conList,historyList);
		}
		ContextHolder.sendRedirect(ContextHolder.findInstance().getContextUri()
				+ "/CustomerAction/gotoList.do");
	}

	private List<ContactInfo> parseToContactInfo(String contacts) {
		List<ContactInfo> result = new ArrayList<ContactInfo>();
		if (contacts == null || contacts.indexOf("-") == 0) {
			return result;
		}
		if (contacts == null || contacts.trim().length() == 0) {
			return result;
		}
		String[] conList = contacts.trim().split(",");
		for (String str : conList) {
			String[] nameAndPhone = str.split("-");
			ContactInfo info = new ContactInfo();
			info.setContactPerson(nameAndPhone[0]);
			info.setContactPhone(nameAndPhone[1]);
			info.setID(IDCreator.getSingleId());
			result.add(info);
		}
		return result;
	}

	private List<BrandVisitHistory> parseToHistorys(String content) {
		List<BrandVisitHistory> result = new ArrayList<BrandVisitHistory>();
		if (content == null || content.trim().length() == 0) {
			return result;
		}
		String[] conList = content.trim().split("-");
		for (String str : conList) {
			BrandVisitHistory history = new BrandVisitHistory();
			history.setID(IDCreator.getSingleId());
			history.setDetailInfo(str);
			result.add(history);
		}
		return result;
	}

	public void getDetail() {
		String id = ContextHolder.findInstance().getRequest()
				.getParameter("itemid");
		Customer customer = CustomerService.instance.getCustomerById(id);
		String json = JsonUtil.parseToJson(customer);
		List<ContactInfo> infos = ContactInfoService.instance
				.getContactInfoByReId(customer.getID());
		String infoStr = JsonUtil.parseToJson(infos);
		List<BrandVisitHistory> historyList = BrandHistoryService.instance.getHistoryByBrandId(customer.getID());
		String historys = JsonUtil.parseToJson(historyList);
		json = json.replace("}", ",'contactInfo':" + infoStr + ", 'historys':" + historys + "}");
		json = json.replaceAll("/n", "");
		json = json.replaceAll("/r", "");
		HttpServletResponse response = ContextHolder.findInstance()
				.getResponse();
		try {
			PrintWriter out = response.getWriter();
			out.write("customer=" + json);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void doDelete() {
		String id = ContextHolder.findInstance().getRequest()
				.getParameter("deleteId");
		System.out.println("| CustomerAction | doDelete | id | " + id);

		Customer customer = CustomerService.instance.getCustomerById(id);
		if (!SecurityUtil.isUserHasRight(customer.getUserId())) {
			ContextHolder.sendRedirect(ContextHolder.findInstance()
					.getContextUri() + "/CustomerAction/gotoList.do");
			return;
		}
		customer.setID(id);
		CustomerService.instance.delete(customer);
		ContactInfoService.instance.deleteByReId(id);
		ContextHolder.sendRedirect(ContextHolder.findInstance().getContextUri()
				+ "/CustomerAction/gotoList.do");
	}

	public void queryDelete() {
		String id = ContextHolder.findInstance().getRequest()
				.getParameter("deleteId");
		System.out.println("| CustomerAction | queryDelete | id | " + id);
		Customer customer = new Customer();
		customer.setID(id);
		CustomerService.instance.delete(customer);
		ContextHolder.sendRedirect(ContextHolder.findInstance().getContextUri()
				+ "/CustomerAction/gotoQuery.do");
	}

	public void conditionSelect() {
		String cusType_s = ContextHolder.findInstance().getRequest()
				.getParameter("cusType_s");
		String customerName_s = ContextHolder.findInstance().getRequest()
				.getParameter("customerName_s");
		String pageNum = ContextHolder.findInstance().getRequest()
				.getParameter("pageNum");
		int num = Integer.valueOf(pageNum);
		int start = (num - 1) * pageSize;
		ContextHolder.reinitParameterToRequest("cusType_s");
		ContextHolder.reinitParameterToRequest("customerName_s");
		ContextHolder.setRequestAttribute("pageNum", num);
		String sql = "select * from customer where cusType like '%" + cusType_s
				+ "%' and customerName like '%" + customerName_s
				+ "%' order by id limit " + start + "," + pageSize;
		List<Customer> allCustomer = CustomerService.instance
				.selectByCondition(sql);
		allCustomer = getUserBindCustomer(allCustomer);
		ContextHolder.setRequestAttribute("allCustomer", allCustomer);
		ContextHolder.forward("/WEB-INF/jsp/customer/update.jsp");
	}

	public void conditionQuery() {
		String cusType_s = ContextHolder.findInstance().getRequest()
				.getParameter("cusType_s");
		String customerName_s = ContextHolder.findInstance().getRequest()
				.getParameter("customerName_s");
		String sql = "select * from customer where cusType like '%" + cusType_s
				+ "%' and customerName like '%" + customerName_s + "%'";
		List<Customer> allCustomer = CustomerService.instance
				.selectByCondition(sql);
		ContextHolder.setRequestAttribute("allCustomer", allCustomer);
		ContextHolder.forward("/WEB-INF/jsp/customer/query.jsp");
	}

	private List<Customer> getUserBindCustomer(List<Customer> customers) {
		List<Customer> result = new ArrayList<Customer>();
		for (int i = 0; i < customers.size(); i++) {
			if (SecurityUtil.isUserHasRight(customers.get(i).getUserId())) {
				result.add(customers.get(i));
			}
		}
		return result;
	}
}
